//
//  GPRequest.swift
//  SeaTransportManage
//
//  Created by guopengwen on 2021/11/29.
//

import UIKit
import Foundation
import Alamofire

typealias ApiCompleted = (_ isSuccess: Bool, _ data: Any, _ err: (code: Int, msg: String)?) -> ()
let Authorization_Key  = "Authorization"
let TokenInvalidCode = 401


class GPRequestApi {
    
    var _header: [String: String]  = ["Content-Type": "application/json"]
    let kDefaultErrorDesc: String = "接口请求出错啦~"
        
    func getRequestHeader() -> Dictionary<String, String> {
        let Authorization = UserDefaults.standard.object(forKey: Authorization_Key)
        if(Authorization != nil) {
            _header["Authorization"] = Authorization as? String
        }
        return _header;
    }
    
    
    func request_get(_ url: String, parameters: [String: Any]? = nil, completed: @escaping ApiCompleted) {
        let request_header = getRequestHeader()
        Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: request_header).responseJSON { response in
            switch response.result {
                case let .success(value):
                    if let value = value as? [String: Any], let status = value["code"] as? Int, status != 200 {
                        if(status == TokenInvalidCode) {
                            self.handleTokenInvalidAction()
                        } else {
                            completed(false, [:], (status, (value["msg"] as? String) ?? ""))
                        }
                    } else {
                        completed(true, value, nil)
                    }
                case let .failure(error as NSError):
                    if error.code < 0 {
                        completed(false, [:], (error.code, error.localizedDescription))
                    } else {
                        completed(false,[:], (error.code, self.kDefaultErrorDesc))
                    }
                default:
                    completed(false, [:], (0, "unknow error"))
            }
        }
    }
    
    func request_post(_ url: String, parameters: [String: Any]? = nil, completed: @escaping ApiCompleted) {
        var request_header = getRequestHeader()
        if(url.hasSuffix("prod-api/client/login") && request_header["Authorization"] != nil) {
            request_header.removeValue(forKey: "Authorization")
        }
        Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: request_header).responseJSON  { response in
            switch response.result {
                case let .success(value):
                    if let value = value as? [String: Any], let status = value["code"] as? Int, status != 200 {
                        if(status == TokenInvalidCode) {
                            self.handleTokenInvalidAction()
                        } else {
                            completed(false, [:], (status, (value["msg"] as? String) ?? ""))
                        }
                    } else {
                        completed(true, value, nil)
                    }
                case let .failure(error as NSError):
                    if error.code < 0 {
                        completed(false, [:], (error.code, error.localizedDescription))
                    } else {
                        completed(false, [:], (error.code, self.kDefaultErrorDesc))
                    }
                default:
                    completed(false, [:], (0, "unknow error"))
            }
        }
    }
    
    func request_put(_ url: String, parameters: [String: Any]? = nil, completed: @escaping ApiCompleted) {
        let request_header = getRequestHeader()
        Alamofire.request(url, method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: request_header).responseJSON  { response in
            switch response.result {
                case let .success(value):
                    if let value = value as? [String: Any], let status = value["code"] as? Int, status != 200 {
                        if(status == TokenInvalidCode) {
                            self.handleTokenInvalidAction()
                        } else {
                            completed(false, [:], (status, (value["msg"] as? String) ?? ""))
                        }
                    } else {
                        completed(true, value, nil)
                    }
                case let .failure(error as NSError):
                    if error.code < 0 {
                        completed(false, [:], (error.code, error.localizedDescription))
                    } else {
                        completed(false, [:], (error.code, self.kDefaultErrorDesc))
                    }
                default:
                    completed(false, [:], (0, "unknow error"))
            }
        }
    }
    
    func request_uploadWithFile(_ url: String, data: Data, completed: @escaping ApiCompleted) {
        var request_header = getRequestHeader()
        request_header.removeValue(forKey: "Content-Type")
        Alamofire.upload(
            multipartFormData: { formData in
                formData.append(data, withName: "file", fileName: "file.jpg", mimeType: "image/jpeg")
            },
            to: url,
            method: .post,
            headers: request_header,
            encodingCompletion: { (encodingResult) in
                switch encodingResult{
                case .success(let upload,_,_):
                    upload.responseJSON(completionHandler: { (response) in
                        switch response.result {
                            case let .success(value):
                                if let value = value as? [String: Any], let status = value["code"] as? Int, status != 200 {
                                    if(status == TokenInvalidCode) {
                                        self.handleTokenInvalidAction()
                                    } else {
                                        completed(false, [:], (status, (value["msg"] as? String) ?? ""))
                                    }
                                } else {
                                    completed(true, value, nil)
                                }
                            case let .failure(error as NSError):
                                if error.code < 0 {
                                    completed(false, [:], (error.code, error.localizedDescription))
                                } else {
                                    completed(false, [:], (error.code, self.kDefaultErrorDesc))
                                }
                            default:
                                completed(false, [:], (0, "unknow error"))
                        }
                    })
                    
                case .failure:
                    completed(false, [:], (0, "上传失败"))
                }
                
        })
    }
    
    func handleTokenInvalidAction() {
        UserDefaults.standard.removeObject(forKey: Authorization_Key)
        let loginVC: STLoginViewController = STLoginViewController.init()
        UIApplication.shared.keyWindow?.rootViewController = loginVC
    }
    
}

